/// Dart 基础控制流实现
/// 包含循环、分支和错误处理示例

// 循环示例
void loopExamples() {
  print('=== 循环示例 ===');

  // for 循环
  var message = 'Dart ';
  for (var i = 0; i < 5; i++) {
    message += i.toString();
  }
  print(message); // Dart 01234

  // for-in 循环
  var numbers = [1, 2, 3];
  for (var number in numbers) {
    print(number);
  }

  // while 循环
  var count = 0;
  while (count < 3) {
    print('Count: $count');
    count++;
  }

  // do-while 循环
  var i = 0;
  do {
    print('Do-While: $i');
    i++;
  } while (i < 3);
}

// 分支示例
void branchExamples() {
  print('\n=== 分支示例 ===');

  var year = 2025;
  var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];

  // if-else
  if (year >= 2001) {
    print('21st century');
  } else if (year >= 1901) {
    print('20th century');
  }

  // for-in 带条件
  for (final object in flybyObjects) {
    if (object.startsWith('S')) {
      print('Found $object');
    }
  }

  // switch-case
  var command = 'OPEN';
  switch (command) {
    case 'CLOSED':
      print('Closed');
      break;
    case 'OPEN':
      print('Open');
      break;
    default:
      print('Unknown');
  }
}

// 错误处理示例
void errorHandlingExamples() {
  print('\n=== 错误处理示例 ===');

  // try-catch
  try {
    var result = 100 ~/ 0;
    print(result);
  } catch (e) {
    print('捕获异常: $e');
  }

  // try-catch-finally
  try {
    throw FormatException('格式错误');
  } on FormatException catch (e) {
    print('特定异常: ${e.message}');
  } catch (e) {
    print('其他异常: $e');
  } finally {
    print('最终都会执行');
  }
}

/// 运行所有示例
void runAllExamples() {
  loopExamples();
  branchExamples();
  errorHandlingExamples();
}
